from invidious import VideoItem as video

from src.vobjects.player import Player
from src.vobjects.item import Item

from src.config import Config
from src.utils import *

from datetime import timedelta, datetime
import time
import os

class Video(video):

    watched_time = 0

    def to_item(self, inHistory: bool=False, isHistoryList: bool=False):
        title = self.title
        fstr = f"[{timedelta(seconds=self.lengthSeconds)}]"
        sstr = self.author
        tstr = f"({self.publishedText})"
        subtitle = ""

        if inHistory: 
            subtitle = "[+]"
            fstr = f"({timedelta(seconds=self.lengthSeconds-self.watched_time)})"
            if isHistoryList:
                ts = datetime.fromtimestamp(self.published)
                tstr = str(ts.strftime('%H:%M %d.%m.%Y'))

        check_published = (self.publishedText != "" and self.publishedText[0] == "0" and self.lengthSeconds == 0)
        if hasattr(self, 'liveNow') and (self.liveNow or check_published):
            fstr = "[LIVE NOW]"
            subtitle = "[•]"

        status = {
            "views" : convert_big_nums(self.viewCount),
        }
        if hasattr(self, "url"): status['url'] = self.url

        if self.watched_time != 0: 
            subtitle = "[+]"
            status["watched time"] = f"{self.watched_time}s"

        return Item(title, fstr, sstr, tstr, self, subtitle, status=status)

    def from_json(self, jsn):
        self.title          = jsn['title']
        self.lengthSeconds  = jsn['lengthSeconds']
        self.author         = jsn['author']
        self.published      = jsn['published']
        self.url            = jsn['url']
        self.publishedText  = datetime.fromtimestamp(self.published).strftime("%H:%M %d.%m.%Y")

        if 'videoId' in jsn: self.videoId = jsn['videoId']
        if 'watched_time' in jsn: self.watched_time = jsn['watched_time']

        return self

    def to_json(self):
        jsn = {
            "title" : self.title,
            "videoId" : self.videoId,
            "lengthSeconds" : self.lengthSeconds,
            "author" : self.author,
            "published" : self.published,
            "url" : self.url,
            "watched_time" : self.watched_time
        }

        return jsn

    def play(self, play_option: str="", mirror: str="", history=None, time_opt: str=""):
        link = mirror + "/watch?v=" + self.videoId

        player = Player()
        player.play(link, play_option, self, history, time_opt)

    def download(self, mirror: str=""):
        config = Config()

        link = mirror + "/watch?v=" + self.videoId
        
        command = "yt-dlp " + link + f" --output '{config.VideoDownloadDirectory}/{self.title}.webm'"

        print(command)

        os.system(command)

